<template>
  <div class="attendance-config">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('attendance.config') }}</span>
        <div :class="{'header-actions': true, 'mobile-header-actions': isMobile}">
          <el-radio-group v-model="configType" size="small" class="view-switch"  v-if="isAdmin">
            <el-radio-button label="global">{{ $t('system.globalAttendanceRules') }}</el-radio-button>
            <el-radio-button  label="course">{{ $t('attendance.config') }}</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      
      <!-- 搜索条件 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item :label="$t('course.title')">
            <el-select v-model="searchForm.courseId" :placeholder="$t('attendance.pleaseSelectCourse')" clearable>
              <el-option 
                v-for="course in courses" 
                :key="course.id" 
                :label="course.name" 
                :value="course.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchConfig">{{ $t('common.search') }}</el-button>
            <el-button @click="resetSearch">{{ $t('common.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 配置表单 -->
      <div class="config-form-container" v-loading="loading">
        <el-form :model="configForm" :rules="rules" ref="configForm" label-width="120px">
          <!-- 课程配置时才显示课程选择 -->
          <el-form-item :label="$t('course.title')" v-if="configType === 'course'">
            <el-select v-model="configForm.courseId" :placeholder="$t('attendance.pleaseSelectCourse')" :disabled="!isAdmin">
              <el-option 
                v-for="course in courses" 
                :key="course.id" 
                :label="course.name" 
                :value="course.id">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item :label="$t('system.startDate')" prop="semesterStart">
            <el-date-picker
              v-model="configForm.semesterStart"
              type="date"
              :placeholder="$t('common.pleaseSelect')"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item :label="$t('system.endDate')" prop="semesterEnd">
            <el-date-picker
              v-model="configForm.semesterEnd"
              type="date"
              :placeholder="$t('common.pleaseSelect')"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item :label="$t('system.startTime')" prop="checkInTime">
            <el-time-picker
              v-model="configForm.checkInTime"
              :placeholder="$t('common.pleaseSelect')"
              value-format="HH:mm:ss">
            </el-time-picker>
          </el-form-item>
          
          <el-form-item :label="$t('system.endTime')" prop="checkInEndTime">
            <el-time-picker
              v-model="configForm.checkInEndTime"
              :placeholder="$t('common.pleaseSelect')"
              value-format="HH:mm:ss">
            </el-time-picker>
          </el-form-item>
          
          <el-form-item :label="$t('system.locationRequirement')" prop="locationRequired">
            <el-switch
              v-model="configForm.locationRequired"
              :active-value="1"
              :inactive-value="0">
            </el-switch>
          </el-form-item>
          
          <el-form-item :label="$t('attendance.distance') + '(' + $t('attendance.meter') + ')'" prop="validDistance" v-if="configForm.locationRequired === 1">
            <el-input-number v-model="configForm.validDistance" :min="10" :max="1000" :step="10"></el-input-number>
          </el-form-item>
          
          <el-form-item :label="$t('attendance.checkLocation')" v-if="configForm.locationRequired === 1">
            <el-row :gutter="10">
              <el-col :span="11">
                <el-input v-model="configForm.locationLatitude" :placeholder="$t('attendance.latitude')"></el-input>
              </el-col>
              <el-col :span="2" style="text-align: center;">-</el-col>
              <el-col :span="11">
                <el-input v-model="configForm.locationLongitude" :placeholder="$t('attendance.longitude')"></el-input>
              </el-col>
            </el-row>
            <el-button type="text" @click="getCurrentLocation">{{ $t('system.getLocation') }}</el-button>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitLoading">{{ $t('system.saveSettings') }}</el-button>
            <el-button @click="resetForm">{{ $t('system.resetSettings') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 配置说明 -->
      <div class="config-tips">
        <el-alert
          :title="$t('attendance.config')"
          type="info"
          :description="$t('attendance.rules')"
          show-icon
          :closable="false">
        </el-alert>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "AttendanceConfig",
  data() {
    return {
      userInfo: JSON.parse(sessionStorage.getItem("userInfo")),
      isTeacher: false,
      isAdmin: false,
      loading: false,
      submitLoading: false,
      configType: 'course', // 配置类型：global-全局配置，course-课程配置
      isMobile: false, // 移动端标记
      screenWidth: document.body.clientWidth,
      
      // 搜索表单
      searchForm: {
        courseId: null
      },
      
      // 配置表单
      configForm: {
        id: null,
        courseId: null,
        semesterStart: '',
        semesterEnd: '',
        checkInTime: '',
        checkInEndTime: '',
        locationRequired: 0,
        validDistance: 100,
        locationLatitude: null,
        locationLongitude: null
      },
      
      // 表单验证规则
      rules: {
        courseId: [
          { required: true, message: this.$t('attendance.pleaseSelectCourse'), trigger: 'change' }
        ],
        semesterStart: [
          { required: true, message: this.$t('attendance.selectSemesterStart'), trigger: 'change' }
        ],
        semesterEnd: [
          { required: true, message: this.$t('attendance.selectSemesterEnd'), trigger: 'change' }
        ],
        checkInTime: [
          { required: true, message: this.$t('attendance.selectCheckInTime'), trigger: 'change' }
        ],
        checkInEndTime: [
          { required: true, message: this.$t('attendance.selectCheckInEndTime'), trigger: 'change' }
        ]
      },
      
      // 课程列表
      courses: []
    }
  },
  created() {
    this.checkUserRole();
    this.initData();
    this.checkScreenSize();
  },
  mounted() {
    window.addEventListener('resize', this.checkScreenSize);
    this.checkScreenSize();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkScreenSize);
  },
  watch: {
    configType(newVal) {
      this.resetForm();
      if (newVal === 'global') {
        this.getGlobalConfig();
      } else {
        this.getCourses();
      }
    }
  },
  methods: {
    // 检查屏幕尺寸并设置相应的布局
    checkScreenSize() {
      this.screenWidth = document.body.clientWidth;
      this.isMobile = this.screenWidth < 768;
    },
    checkUserRole() {
      // 检查用户角色
      if (this.userInfo && this.userInfo.roleName) {
        this.isTeacher = this.userInfo.roleName.includes('teacher');
        this.isAdmin = this.userInfo.roleName.includes('admin');
      }
    },
    initData() {
      // 获取课程列表
      this.getCourses();
    },
    getCourses() {
      const userId = this.userInfo.userId;
      let url = this.isAdmin ? '/course/page' : `/course/teacher/${userId}`;
      
      this.$axios.get(url).then(res => {
        //console.log(url,res)
        if (res.code === 200) {
          if (this.isAdmin) {
            this.courses = res.data.records || [];
          } else {
            this.courses = res.data || [];
          }
          
          // 如果只有一个课程，自动选择
          if (this.courses.length === 1) {
            this.searchForm.courseId = this.courses[0].id;
            this.searchConfig();
          }
        }
      }).catch(err => {
        console.error(this.$t('course.getCoursesError'), err);
        this.$message.error(this.$t('course.getCoursesError'));
      });
    },
    searchConfig() {
      if (!this.searchForm.courseId) {
        this.$message.warning(this.$t('attendance.pleaseSelectCourse'));
        return;
      }
      
      this.loading = true;
      
      this.$axios.get(`/attendance/config/course`, {
        params: {
          courseId: this.searchForm.courseId
        }
      }).then(res => {
        if (res.code === 200) {
          const config = res.data;
          if (config) {
            this.configForm = { ...config };
            // 设置课程ID
            this.configForm.courseId = this.searchForm.courseId;
            
            // 确保locationRequired值为正确的类型
            this.configForm.locationRequired = config.locationRequired ? 1 : 0;
          } else {
            // 没有配置，使用默认值
            this.resetForm();
            this.configForm.courseId = this.searchForm.courseId;
          }
        } else {
          this.$message.error(res.data.msg || this.$t('attendance.getConfigError'));
        }
      }).catch(err => {
        console.error(this.$t('attendance.getConfigError'), err);
        this.$message.error(this.$t('attendance.getConfigError'));
      }).finally(() => {
        this.loading = false;
      });
    },
    resetSearch() {
      this.searchForm = {
        courseId: null
      };
    },
    submitForm() {
      this.$refs.configForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          
          // 验证时间范围
          if (this.configForm.checkInTime >= this.configForm.checkInEndTime) {
            this.$message.error(this.$t('attendance.checkInTimeError'));
            this.submitLoading = false;
            return;
          }
          
          // 验证学期时间范围
          if (this.configForm.semesterStart >= this.configForm.semesterEnd) {
            this.$message.error(this.$t('attendance.semesterTimeError'));
            this.submitLoading = false;
            return;
          }
          
          // 将locationRequired转换为布尔值
          const configData = {
            ...this.configForm,
            locationRequired: this.configForm.locationRequired === 1
          };
          
          const url = this.configType === 'global' ? '/attendance/config/global' : '/attendance/config/course';
          
          this.$axios.post(url, configData).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t('attendance.configSaveSuccess'));
              if (this.configType === 'global') {
                this.getGlobalConfig();
              } else {
                this.searchConfig();
              }
            } else {
              this.$message.error(res.data.msg || this.$t('attendance.configSaveError'));
            }
          }).catch(err => {
            console.error(this.$t('attendance.configSaveError'), err);
            this.$message.error(this.$t('attendance.configSaveError'));
          }).finally(() => {
            this.submitLoading = false;
          });
        }
      });
    },
    resetForm() {
      this.configForm = {
        id: null,
        courseId: this.searchForm.courseId,
        semesterStart: '',
        semesterEnd: '',
        checkInTime: '',
        checkInEndTime: '',
        locationRequired: 0,
        validDistance: 100,
        locationLatitude: null,
        locationLongitude: null
      };
    },
    getCurrentLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          position => {
            this.configForm.locationLatitude = position.coords.latitude;
            this.configForm.locationLongitude = position.coords.longitude;
            this.$message.success(this.$t('common.operationSuccess'));
          },
          error => {
            console.error(this.$t('attendance.locationNotAvailable'), error);
            this.$message.error(this.$t('attendance.locationNotAvailable'));
          }
        );
      } else {
        this.$message.warning(this.$t('attendance.locationNotAvailable'));
      }
    },
    getGlobalConfig() {
      this.loading = true;
      this.$axios.get('/attendance/config/global').then(res => {
        if (res.code === 200) {
          const config = res.data;
          if (config) {
            this.configForm = { ...config };
            
            // 确保locationRequired值为正确的类型
            this.configForm.locationRequired = config.locationRequired ? 1 : 0;
          } else {
            this.resetForm();
          }
        } else {
          this.$message.error(res.data.msg || this.$t('attendance.getConfigError'));
        }
      }).catch(err => {
        console.error(this.$t('attendance.getConfigError'), err);
        this.$message.error(this.$t('attendance.getConfigError'));
      }).finally(() => {
        this.loading = false;
      });
    }
  }
}
</script>

<style scoped>
.attendance-config {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.config-form-container {
  margin-top: 20px;
  max-width: 800px;
}

.config-tips {
  margin-top: 30px;
}

/* 头部操作区样式 */
.header-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  float: right;
}

.mobile-header-actions {
  flex-direction: column;
  align-items: flex-end;
  float: none;
  margin-top: 10px;
}

.mobile-header-actions .view-switch {
  margin-bottom: 10px;
  width: 100%;
}

@media screen and (max-width: 768px) {
  .attendance-config {
    padding: 10px;
  }
  
  .clearfix {
    display: flex;
    flex-direction: column;
  }
  
  .view-switch {
    display: flex;
    width: 100%;
  }
  
  .view-switch .el-radio-button {
    flex: 1;
  }
  
  .view-switch .el-radio-button__inner {
    width: 100%;
  }
  
  .config-form-container {
    margin-top: 15px;
    max-width: 100%;
  }
  
  .el-form-item {
    width: 100%;
    margin-right: 0;
  }
  
  .el-select, .el-date-picker, .el-time-picker, .el-input-number {
    width: 100% !important;
  }
  
  .el-form-item__content {
    width: 100%;
  }
}
</style> 